package service

import (
	"encoding/json"
	"fmt"
	xnet "git.bluexii.cn/utils/net"
	"strconv"
	"gomuisc/models/mysql"
	"gomuisc/service/spider/constants"
	"gomuisc/service/spider/encrypt"
	url2 "net/url"
	"regexp"
)

func HttpPostMuisc(url string,body interface{})(resp []byte,err error){
	//获取token
	accessToken,err := GetParams(body);
	if err != nil {
		fmt.Println("请求异常")
		return
	}

	body1 := make(url2.Values)
	body1["params"] = []string{accessToken["params"]}
	body1["encSecKey"] = []string{accessToken["encSecKey"]}

	header := make(map[string]string)
	header["Content-Type"] = "application/x-www-form-urlencoded"

	resp,err = xnet.HttpService{}.Init(xnet.InitStruct{}).HttpPost(url,body1.Encode(),header);
	if err != nil {
		fmt.Println(err)
		return
	}
	return
}
func GetParams(body interface{}) (content map[string]string,err error) {

	jsonParams, err := json.Marshal(body)

	content = make(map[string]string)
	randomBytes := encrypt.RandomStr(16)
	params, err := encrypt.AesEncrypt(string(jsonParams), constants.SrcretKey, constants.AseKey)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	params, err = encrypt.AesEncrypt(params, string(randomBytes), constants.AseKey)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	encSecKey := encrypt.RsaEncrypt(string(randomBytes), constants.PubKey, constants.Modulus)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	content["params"] = string(params)
	content["encSecKey"] = string(encSecKey)
	return
}
func Http_get(url string)(singles []mysql.Single)  {
	header := make(map[string]string)
	header["Content-Type"] = "application/x-www-form-urlencoded"
	str,err := xnet.HttpService{}.Init(xnet.InitStruct{}).HttpGet(url,header);
	if err !=nil{

	}

	reg1 := regexp.MustCompile(`<ul class="f-hide">(.*?)<\/ul>`)
	if reg1 == nil {
		fmt.Println("regexp err")
		return
	}
	//根据规则提取关键信息
	str1 := reg1.FindAllStringSubmatch(string(str), -1)
	fmt.Println("新的字符串是",str1)
	newstr := str1[0][0]
	fmt.Println("新的字符串是",newstr)

	////解析正则表达式，如果成功返回解释器
	reg2 := regexp.MustCompile(`<a.*?href="/song\?id=(.*?)".*?>(.+?)</a>`)
	if reg2 == nil {
		fmt.Println("regexp err")
		return
	}
	//根据规则提取关键信息
	result1 := reg2.FindAllStringSubmatch(newstr, -1)
	//fmt.Println("result1 = ", result1)

	singles = make([]mysql.Single,0,len(result1))
	for _,v := range result1{
		i,_ := strconv.Atoi(v[1])
		ar := mysql.Single{
			Song_id:i,
			Song_name:v[2],
		}
		singles  = append(singles,ar)
	}
	return
}


